package com.das.mechanic_alone.mvp.view.maintain;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.airbnb.lottie.LottieAnimationView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.das.mechanic_alone.mvp.contract.maintain.X3MainNewTainContract;
import com.das.mechanic_alone.mvp.presenter.maintain.X3MainNewTainPresenter;
import com.das.mechanic_alone.mvp.view.alone.X3AloneActivity;
import com.das.mechanic_base.R;
import com.das.mechanic_base.R2;
import com.das.mechanic_base.adapter.maintain.X3AloneAdapter;
import com.das.mechanic_base.adapter.maintain.X3TainCancelAdapter;
import com.das.mechanic_base.app.X3AppRouterConstants;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.app.X3MyApp;
import com.das.mechanic_base.app.X3RouterCenter;
import com.das.mechanic_base.base.X3BaseActivity;
import com.das.mechanic_base.bean.alone.AloneTitleBean;
import com.das.mechanic_base.bean.alone.UnCompleteBean;
import com.das.mechanic_base.bean.camera.CameraBean;
import com.das.mechanic_base.bean.common.UploadVideoBean;
import com.das.mechanic_base.bean.create.SaveWorkSuccessBean;
import com.das.mechanic_base.bean.create.ServiceInfoBean;
import com.das.mechanic_base.bean.even.DeleteFriends;
import com.das.mechanic_base.bean.live.FetchLiveBean;
import com.das.mechanic_base.bean.main.CarPicAndColorBean;
import com.das.mechanic_base.bean.main.HomeMainCarBean;
import com.das.mechanic_base.bean.main.UpadateReceBean;
import com.das.mechanic_base.bean.maintain.AdvanceTimeBean;
import com.das.mechanic_base.bean.maintain.CancelWorkBean;
import com.das.mechanic_base.bean.maintain.WorkBaseHeaderBean;
import com.das.mechanic_base.def.finish.X3WorkType;
import com.das.mechanic_base.mvp.view.camera.X3CameraPhotoActivity;
import com.das.mechanic_base.service.UploadVideoService;
import com.das.mechanic_base.utils.LanguageUtiles;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.X3BaseDialogUtil;
import com.das.mechanic_base.utils.X3FileUtils;
import com.das.mechanic_base.utils.X3GlideNewUtils;
import com.das.mechanic_base.utils.X3Permission;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StatusBarUtil;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3TimeUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.das.mechanic_base.utils.X3Utils;
import com.das.mechanic_base.widget.X3BottomAffirmCarDialog;
import com.das.mechanic_base.widget.X3BottomAlreadyAloneServiceDialog;
import com.das.mechanic_base.widget.X3BottomStaffDialog;
import com.das.mechanic_base.widget.X3CancelPopUpWindow;
import com.das.mechanic_base.widget.X3HomeNoticePop;
import com.das.mechanic_base.widget.X3MarqueeText;
import com.das.mechanic_base.widget.X3MemberButtonView;
import com.das.mechanic_base.widget.X3ModifyHeaderView;
import com.das.mechanic_base.widget.X3NoticeDialog;
import com.das.mechanic_base.widget.X3PointDialog;
import com.das.mechanic_base.widget.X3SelectLiveTypeDialog;
import com.das.mechanic_base.widget.X3UnCompleteDialog;
import com.google.android.material.appbar.AppBarLayout;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.umeng.analytics.MobclickAgent;
import com.yhao.floatwindow.FloatWindow;
import com.yhao.floatwindow.IFloatWindowImpl;
import com.yhao.floatwindow.MoveType;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.das.mechanic_base.app.X3Constent.CODE_CAMERA_VIN_REQUEST;

@Route(path = X3AppRouterConstants.Router.MAIN_TAIN)
public class X3MainNewTainActivity extends X3BaseActivity<X3MainNewTainPresenter> implements X3MainNewTainContract.View, X3CancelPopUpWindow.IOpenCameraClick, X3TainCancelAdapter.IOnClick, X3UnCompleteDialog.IOnJumpToItem, X3BottomStaffDialog.IOnSaveWorkBase {

    @BindView(R2.id.rlv_main_tain)
    RecyclerView rlv_main_tain;
    @BindView(R2.id.tv_title)
    X3MarqueeText tv_title;
    @BindView(R2.id.btn_submit)
    X3MemberButtonView btn_submit;
    @BindView(R2.id.app_bar)
    AppBarLayout app_bar;
    @BindView(R2.id.iv_cancel)
    ImageView iv_cancel;
    @BindView(R2.id.btn_before)
    X3MemberButtonView btn_before;
    @BindView(R2.id.iv_preview)
    ImageView iv_preview;
    @BindView(R2.id.iv_header_one)
    ImageView iv_header_one;
    @BindView(R2.id.iv_header_two)
    ImageView iv_header_two;
    @BindView(R2.id.tv_header_one)
    TextView tv_header_one;
    @BindView(R2.id.tv_header_two)
    TextView tv_header_two;
    @BindView(R2.id.v_header_two)
    View v_header_two;
    @BindView(R2.id.cl_header)
    CoordinatorLayout cl_header;
    @BindView(R2.id.tv_live)
    TextView tv_live;
    @BindView(R2.id.iv_service_car)
    ImageView iv_service_car;
    @BindView(R2.id.tv_service_num)
    TextView tv_service_num;
    @BindView(R2.id.lav)
    LottieAnimationView lav;

    private List<String> titleList;
    private String carNum;
    private String startTime;
    private String completeTime;
    private CountDownTimer timer;
    private long allTime;
    private X3AloneAdapter aloneAdapter;

    List<AloneTitleBean> aloneTitleBeans;
    private long carId;
    private X3CancelPopUpWindow cancelPopUpWindow;
    private X3BaseDialogUtil dialogUtil;
    private X3NoticeDialog noticeDialog;

    private List<WorkBaseHeaderBean.StaffBaseEntityListBean> staffList;

    /**
     * 判断施工是否开始
     */
    private boolean isStart;

    private long timeOutNum;
    private boolean isChina;

    private boolean isContainMe;
    private long workBaseStatus;
    private long reportStatus;
    private X3BottomAlreadyAloneServiceDialog alreadyAloneServiceDialog;
    private X3BottomAffirmCarDialog carDialog;
    private boolean quickCheck;
    private boolean needUpdateMileAndDate;
    private HomeMainCarBean carBean;
    private String lastName;
    private long liveRoomId;
    private X3HomeNoticePop noticePop;
    private boolean isUploadVideo =false;
    private List<UploadVideoBean> uploadVideoList;
    private List<CancelWorkBean> cancelList;
    private boolean isOne;
    private boolean isNotSupportLive;
    private X3UnCompleteDialog unCompleteDialog;
    private X3BottomStaffDialog staffDialog;
    private String externalInspectionOrderId;

    @Override
    protected int getLayoutId() {
        EventBus.getDefault().register(this);
        return R.layout.x3_activity_main_new_tain;
    }

    @Override
    protected void initView() {
        isNotSupportLive = (boolean) SpHelper.getData(X3Constent.IS_OPEN_SDK, false);

        tv_live.setVisibility(isNotSupportLive ? View.GONE : View.VISIBLE);
        cl_header.setPadding(0, X3StatusBarUtil.getStatusBarHeight(this),0,0);
        X3StatusBarUtil.darkMode(this);
        rlv_main_tain.setLayoutManager(new LinearLayoutManager(this));

        aloneAdapter = new X3AloneAdapter(this, providerWorkBaseId());
        rlv_main_tain.setAdapter(aloneAdapter);

        isChina = LanguageUtiles.isZhRCN();
        initBtn();
    }

    /**
     * 实现三个按钮的点击事件
     */
    private void initBtn() {
        btn_before.setiOnClickAffirm(() -> {
            if (!isContainMe) {
                X3ToastUtils.showMessage(getString(R.string.x3_user_no_index));
                return;
            }
            // 提前施工
            if (mPresenter != null) {
                mPresenter.updateAdavancService();
            }
        });
        btn_submit.setiOnNoClickAffirm(() -> {
            // 未完成点击时 需要告诉用户哪个检测点没有完成
            if (mPresenter != null) {
                mPresenter.getUnCompleteList(providerWorkBaseId());
            }
        });
        btn_submit.setiOnClickAffirm(() -> {
            if (workBaseStatus <= 1) {
                if (!isContainMe) {
                    X3ToastUtils.showMessage(getString(R.string.x3_user_no_index));
                    return;
                }
                /**
                 * 点击发布 先调getReceiveBase 看看需不需要弹出 更新里程和日期的弹框。
                 * 需要的话先更新 里程和日期，成功之后 在调用completeWorkBase.
                 * 结束施工之后 在调用updateReceiveBaseForCar 就是更新车辆基本信息的接口
                 */
                if (quickCheck) {
                    if (mPresenter != null) {
                        mPresenter.getReceiveBase(providerReceiveBaseId(),true);
                    }
                }else {
                    if (mPresenter != null) {
                        mPresenter.completeWorkBase(providerWorkBaseId(),null,false);
                    }
                }

            }else {
                /**
                 * 预览检测报告
                 */
                Bundle bundle = new Bundle();
                bundle.putBoolean("isDark",true);
                bundle.putString("title","检测单预览检测报告页");
                bundle.putString("path", X3Constent.HOME_FINISH_DETAIL_MAIN_URL+"workBaseId=" + providerWorkBaseId() + "&carNum=" + carNum + "&type=preview");
                X3RouterCenter.startNavigate(X3AppRouterConstants.Router.GROUND_PUSH,bundle);

            }


        });
    }

    @Override
    public void getWorkBaseHeaderInfo(WorkBaseHeaderBean headerBean) {
        hideLoading();
        startTime = headerBean.getStartTime();
        completeTime = headerBean.getCompleteTime();
        carNum = headerBean.getCarNum();
        carId = headerBean.getCarId();
        workBaseStatus = headerBean.getWorkBaseStatus();
        reportStatus = headerBean.getReportStatus();
        quickCheck = headerBean.isQuickCheck();
        liveRoomId = headerBean.getLiveRoomId();
        this.externalInspectionOrderId = headerBean.getExternalInspectionOrderId();

        if (tv_service_num.getVisibility() == View.GONE && workBaseStatus == 1 && mPresenter != null) {
            mPresenter.getDetectionServiceList();
        }
        /**
         * 根据此字段 判断此检测报告是否需要审核之后发布
         */
        if (reportStatus == 0) {
            btn_submit.changeText(getString(R.string.x3_submit_report));
        }else {
            btn_submit.changeText(getString(R.string.x3_publish_report));
        }

        staffList = headerBean.getStaffBaseEntityList();

        if (!X3StringUtils.isListEmpty(staffList)) {
            iv_header_two.setVisibility(staffList.size() == 2 ? View.VISIBLE : View.GONE);
            tv_header_two.setVisibility(staffList.size() == 2 ? View.VISIBLE : View.GONE);
            v_header_two.setVisibility(staffList.size() == 2 ? View.VISIBLE : View.GONE);
            for (int i = 0; i < staffList.size(); i++) {
                if (i == 0) {
                    tv_header_one.setText(staffList.get(i).getName());
                    X3GlideNewUtils.loadCircleImage(this, X3StringUtils.getImageUrl(staffList.get(i).getPortrait()),iv_header_one,R.mipmap.x3_car_owner_header);
                }else {
                    tv_header_two.setText(staffList.get(i).getName());
                    X3GlideNewUtils.loadCircleImage(this, X3StringUtils.getImageUrl(staffList.get(i).getPortrait()),iv_header_two,R.mipmap.x3_car_owner_header);
                }
            }
        }else {
            iv_header_two.setVisibility(View.GONE);
            tv_header_two.setVisibility(View.GONE);
            tv_header_one.setText("");
            iv_header_one.setImageResource(R.mipmap.x3_car_owner_header);
        }

        titleList = headerBean.getServiceBaseNameList();

        String title = "";

        if (titleList != null && titleList.size() > 0) {
            for (int i = 0; i < titleList.size(); i++) {
                if (X3StringUtils.isEmpty(titleList.get(i))) {
                    titleList.remove(i);
                }
            }

            for (int i = 0; i < titleList.size(); i++) {
                if (i == 0) {
                    title = titleList.get(i);
                } else {
                    title = title + ", " + titleList.get(i);
                }
            }
        }

        tv_title.setText(title + "（" + carNum + "）");

        if (headerBean.getWorkBaseStatus() > 1) {
            // 已经结束了
            tv_live.setVisibility(View.GONE);
            iv_preview.setVisibility(View.INVISIBLE);
            btn_submit.changeBtnStatus(true);
            btn_submit.changeText(getString(R.string.x3_view_report));
            isStart = true;
            iv_service_car.setVisibility(View.GONE);
        }else {
            showServiceTime();
            iv_service_car.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public long providerReceiveBaseId() {
        return getIntent().getLongExtra("receiveBaseId",0L);
    }

    @Override
    public void setContainMe(boolean isContainMe) {
        this.isContainMe = isContainMe;
    }

    @Override
    public void showErrorStatus(long status) {
        hideLoading();
        if (status != 1995) {
            return;
        }
        noticeDialog = new X3NoticeDialog(this,getString(R.string.x3_force_quit_main_new),getString(R.string.x3_force_quit));
        noticeDialog.show();
        noticeDialog.getBtn_content().setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
        noticeDialog.setCanceledOnTouchOutside(false);
        noticeDialog.setCancelable(false);
        noticeDialog.getBtn_content().setOnClickListener(v -> {
            // TODO 强制结束施工
            if (mPresenter != null) {
                mPresenter.completeWorkForce();
            }
        });

    }

    @Override
    public void completeWorkForceSuccess() {
        EventBus.getDefault().post("UPDATE_CNACEL_ORDER");
        finish();
    }

    @Override
    public void getStoreLiveRoomSuccess(long size) {
        if (isNotSupportLive) {
            return;
        }
        if (size == 0) {
            if(FloatWindow.get("Live") != null) {
                FloatWindow.destroy("Live");
            }
            if (tv_live != null) {
                tv_live.setVisibility(View.VISIBLE);
            }
            return;
        }
        if (X3Permission.requestPermission(this, 24)) {
            //Log.e("SSSS","弹窗是否有权限:" + (FloatWindow.get("Live") == null));
            if (FloatWindow.get("Live") == null) {
                View liveView = View.inflate(this, R.layout.x3_live_float_view,null);

                FloatWindow
                        .with(getApplicationContext())
                        .setView(liveView)
                        .setParentHeight(X3ScreenUtils.getScreenHeight(this))
                        .setTag("Live")
                        .setMoveType(MoveType.slide)
                        .setFilter(true, X3MainNewTainActivity.class)
                        .setX(X3ScreenUtils.getScreenWidth(this) - X3ScreenUtils.dipToPx(105,this))  //设置控件初始位置
                        .setY(X3ScreenUtils.getScreenHeight(this) * 8 / 10)
                        .setDesktopShow(false)
                        .build();
            }

            if (FloatWindow.get("Live") != null && liveRoomId != 0) {
                FloatWindow.get("Live").show();
            }

            View live1 = FloatWindow.get("Live").getView();
            if (live1 != null) {
                X3MarqueeText tv_content = live1.findViewById(R.id.tv_content);
                tv_content.setText(getString(R.string.x3_live_on));
                ImageView iv_icon = live1.findViewById(R.id.iv_icon);
                Glide.with(this).asGif().load(R.drawable.x3_live_play).into(iv_icon);
            }

            IFloatWindowImpl live = (IFloatWindowImpl) FloatWindow.get("Live");
            if (live == null) {
                return;
            }
            live.setiOnClickFloat(() -> {
                X3RouterCenter.startNavigate(X3AppRouterConstants.Router.LIVE_CAR_LIST,null);

            });
        }
    }

    /**
     * 获取接车单详情
     * @param mainCarBean
     */
    @Override
    public void getReceiveBase(HomeMainCarBean mainCarBean,boolean isShow) {
        hideLoading();
        if (mainCarBean == null) {
            return;
        }
        this.carBean = mainCarBean;
        lastName = mainCarBean.getLastName();
        // 是否需要更新里程和日期
        needUpdateMileAndDate = mainCarBean.isNeedUpdateMileAndDate();
        if (!isShow) {
            return;
        }
        showAffirmCarInfo();
    }

    private void showAffirmCarInfo() {
        if(carDialog == null){
            carDialog = new X3BottomAffirmCarDialog(this);
        }

        carDialog.show();
        carDialog.setCarInfo(providerReceiveBaseId(),needUpdateMileAndDate);
        carDialog.setOnDismissListener(dialog -> btn_submit.reset());
        carDialog.setiOnClick(() -> XXPermissions.with(X3MainNewTainActivity.this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if(all){
                            String path = X3FileUtils.getStoragePath(X3MainNewTainActivity.this, X3FileUtils.MECHANIC_PHOTO_STORAGE_PATH) + "work_tain" + System.currentTimeMillis() + ".jpg";

                            if(X3Constent.isChina()){
                                Bundle bundle = new Bundle();
                                bundle.putString("title",getString(R.string.x3_recognize_vin));
                                bundle.putString("path",path);
                                X3RouterCenter.startNavigateWithResult(X3MainNewTainActivity.this, X3AppRouterConstants.Router.HOME_VIN,bundle,CODE_CAMERA_VIN_REQUEST);
                            } else {
                                Bundle bundle = new Bundle();
                                bundle.putString("title",getString(R.string.x3_recognize_vin));
                                bundle.putString("path",path);
                                X3RouterCenter.startNavigateWithResult(X3MainNewTainActivity.this, X3AppRouterConstants.Router.HOME_CAMERA,bundle,CODE_CAMERA_VIN_REQUEST);
                            }
                        }else {
                            XXPermissions.startPermissionActivity(X3MainNewTainActivity.this,permissions);
                        }

                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        XXPermissions.startPermissionActivity(X3MainNewTainActivity.this,permissions);
                    }
                }));
        carDialog.setiOnUpdate((carBean, map) -> {
            if (needUpdateMileAndDate) {
                if (mPresenter != null) {
                    map.put("workBaseId",providerWorkBaseId());
                    mPresenter.updateCarProductionAndMiles(map,carBean);
                }
            }else {
                if (mPresenter != null) {
                    mPresenter.completeWorkBase(providerWorkBaseId(),carBean,true);
                }
            }

        });
    }

    @Override
    public void completeSuccess() {
        // 结束施工之后需要确认车辆信息
        if (isNotSupportLive) {
            if (X3MyApp.getInstance().iAloneEventCallback != null) {
                X3MyApp.getInstance().iAloneEventCallback.iOnCompleteWork(providerWorkBaseId(),externalInspectionOrderId);
            }
            finish();
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putLong("workBaseId", providerWorkBaseId());
        bundle.putString("carNum",carNum);
        bundle.putLong("reportStatus",reportStatus);
        bundle.putInt("type", X3WorkType.Type_Alone);
        X3RouterCenter.startNavigate(X3AppRouterConstants.Router.WORK_FINISH,bundle);
        finish();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data == null) {
            return;
        }
//        String vin = data.getStringExtra("vinResult");

        switch (requestCode) {
            case CODE_CAMERA_VIN_REQUEST:

                if (carDialog == null) {
                    return;
                }
                if(X3Constent.isChina()){
                    String vinResult = data.getStringExtra("vinResult");
//                this.showLoading("");
                    System.out.println("识别vin码"+vinResult);
                    carDialog.setVin(vinResult);
                }else {
                    String vinPath = data.getStringExtra("path");
                    Luban.with(this)
                            .load(vinPath)
                            .ignoreBy(100)
                            .setTargetDir(X3FileUtils.getStoragePath(this, X3FileUtils.MECHANIC_PHOTO_STORAGE_PATH))
                            .filter(path -> !(TextUtils.isEmpty(vinPath) || vinPath.toLowerCase().endsWith(".gif")))
                            .setCompressListener(new OnCompressListener() {
                                @Override
                                public void onStart() {
                                }

                                @Override
                                public void onSuccess(File file) {
                                    if (mPresenter != null) {
                                        mPresenter.requestVin(file);
                                    }
                                }

                                @Override
                                public void onError(Throwable e) {
                                }
                            }).launch();
                }



                break;


        }
    }

    @Override
    public void uploadCarPicSuccess(CarPicAndColorBean colorBean) {
        // TODO 上传车辆切割图成功
        if (colorBean == null) {
            X3ToastUtils.showMessage(getString(R.string.x3_car_cut_fail));
            if (carDialog != null) {
                carDialog.uploadCarCutSuccess(null);
            }
        }else {
            if (carDialog != null) {
                carDialog.uploadCarCutSuccess(colorBean);
            }
        }
    }

    @Override
    public void getVin(String vin) {
        this.hideLoading();
        if (carDialog == null) {
            return;
        }
        carDialog.setVin(vin);
    }

    @Override
    public void jumpComplete() {
        if(carDialog != null){
            carDialog.dismiss();
        }
        completeSuccess();
    }

    @Override
    public void updateReceiveSuccess(UpadateReceBean upadateReceBean) {
        /**
         * 第一种：获取头像,如果为空的话，生成图片，上传服务器
         * 第二种：如果在接车单填写的lastname和原有的，说明用户更改了名称，那么需要重新生成图片上传
         */
        if (X3StringUtils.isEmpty(upadateReceBean.getCarOwnerUserImgUrl()) || !upadateReceBean.getLastName().equals(lastName)) {
            //获取车辆id
            carId = upadateReceBean.getCarId();
            //生成图片地址
            String coweUserImg = X3ModifyHeaderView.setName(upadateReceBean.getLastName(),upadateReceBean.getFirstName(), this);
            //如果coweUserImg不为空的话，上传头像
            if (!X3StringUtils.isEmpty(coweUserImg)) {
                Log.e("TAG", "-------生成的头像路径------" + coweUserImg+"------"+upadateReceBean.getLastName()+"------" + lastName);
                //获取七牛接口，将图片上传七牛
                mPresenter.uploadHeaderAws(new File(coweUserImg));
            }
        }else {
            completeSuccess();
        }
    }

    @Override
    public long providerCarId() {
        return carId;
    }

    @Override
    public void resetButton() {
        if (carDialog != null) {
            carDialog.resetButtonRest();
        }
    }

    @Override
    public void getSaveService(long num) {
        hideLoading();
        if (num == 0) {
            tv_service_num.setVisibility(View.GONE);
        }else {
            tv_service_num.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void getLiveInfoSuccess(FetchLiveBean fetchLiveBean) {//自身开启直播
        Bundle bundle = new Bundle();
        bundle.putSerializable("FetchLiveBean",fetchLiveBean);
        X3RouterCenter.startNavigate(X3AppRouterConstants.Router.LIVE_MAIN,bundle);

    }

    @Override
    public void getUploadVideoSuccess(List<UploadVideoBean> uploadVideoBean) {
        uploadVideoList = uploadVideoBean;
    }

    @Override
    public void onCompleteWork() {
        EventBus.getDefault().post("UPDATE_CNACEL_ORDER");
    }

    @Override
    public void getUnCompleteListSuccess(List<UnCompleteBean> mList) {
        if (X3StringUtils.isListEmpty(mList)) {
            return;
        }
        if (unCompleteDialog == null) {
            unCompleteDialog = new X3UnCompleteDialog(this);
            unCompleteDialog.setiOnJumpToItem(this);
        }
        unCompleteDialog.show();
        unCompleteDialog.showUnComplete(mList);
    }

    @Override
    public void getWorkBaseSuccess(ServiceInfoBean.WorkBaseBean workBaseBean) {
        if (workBaseBean == null) {
            return;
        }
        workBaseBean.workBaseId = providerWorkBaseId();
        staffDialog = new X3BottomStaffDialog(this);
        staffDialog.setiOnSaveWork(this);
        staffDialog.show();
        staffDialog.assignStaff(workBaseBean,true);
    }

    @Override
    public void iOnJumpToItem(UnCompleteBean unCompleteBean) {
        startAlone(unCompleteBean.toSystemDesc,unCompleteBean.questionDetectionTempletSystemId, unCompleteBean.questionToSystemId,
                false,unCompleteBean.mgtCreate,unCompleteBean.id);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("检测单详情页");
        if (FloatWindow.get("Live") != null && !isNotSupportLive) {
            FloatWindow.get("Live").show();
            View live1 = FloatWindow.get("Live").getView();
            if (live1 != null) {
                X3MarqueeText tv_content = live1.findViewById(R.id.tv_content);
                tv_content.setText(getString(R.string.x3_live_on));
                ImageView iv_icon = live1.findViewById(R.id.iv_icon);
                Glide.with(this).asGif().load(R.drawable.x3_live_play).into(iv_icon);
            }
        }
        if (carDialog != null) {
            carDialog.resetEtCarName();
        }
        if (mPresenter != null) {
            showLoading("");
            mPresenter.obtainWorkBase();
            mPresenter.getReceiveBase(providerReceiveBaseId(),false);
            if (workBaseStatus == 1) {
                mPresenter.getDetectionServiceList();
            }
        }
        if(mPresenter != null && !isNotSupportLive){
            mPresenter.startStoreLiveRoom();
            mPresenter.listLiveUploadVideo(providerWorkBaseId());
        }
    }

    /**
     * 开始进入的时候计算
     */
    private void showServiceTime() {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = new Date(System.currentTimeMillis());
        String nowTime = simpleDateFormat.format(date);
        try {
            long startLong = X3TimeUtils.stringToLong(startTime, "yyyy-MM-dd HH:mm:ss");
            long endLong = X3TimeUtils.stringToLong(completeTime, "yyyy-MM-dd HH:mm:ss");
            long nowLong = X3TimeUtils.stringToLong(nowTime, "yyyy-MM-dd HH:mm:ss");
            allTime = endLong - startLong;
            long resultLong = endLong - nowLong;
            long isStartLong = nowLong - startLong;

            if (isStartLong < 0) {
                // 还没开始
                changeToobarColor(0);
                tv_live.setVisibility(View.GONE);
                iv_service_car.setVisibility(View.GONE);
                //countComeTime(allTime);
            } else {
                tv_live.setVisibility((liveRoomId == 0 && !isNotSupportLive) ? View.VISIBLE : View.GONE);
                if (resultLong > 0) {
                    changeToobarColor(1);
                    countTime(resultLong);
                } else {
                    // 当前已经超时了
                    /**
                     * 超时计算超时时间
                     */
                    timeOutNum = nowLong - endLong;

                    changeToobarColor(2);
                }
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private Handler mHandler = new Handler();

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            long hours = timeOutNum / (1000 * 60 * 60);
            long minutes = (timeOutNum - hours * (1000 * 60 * 60)) / (1000 * 60);
            long seconds = (timeOutNum - hours * (1000 * 60 * 60) - minutes * 1000 * 60) / 1000;

            timeOutNum += 1000;
            mHandler.postDelayed(this,1000);
        }
    };

    /**
     * 提前施工计算
     */
    private void showStartServiceTime() {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = new Date(System.currentTimeMillis());
        String nowTime = simpleDateFormat.format(date);
        try {
            long startLong = X3TimeUtils.stringToLong(startTime, "yyyy-MM-dd HH:mm:ss");
            long endLong = X3TimeUtils.stringToLong(completeTime, "yyyy-MM-dd HH:mm:ss");
            long nowLong = X3TimeUtils.stringToLong(nowTime, "yyyy-MM-dd HH:mm:ss");
            allTime = endLong - startLong;
            long resultLong = endLong - nowLong;

            if (resultLong > 0) {
                changeToobarColor(1);
                countTime(resultLong);
            } else {
                // 当前已经超时了
                changeToobarColor(2);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void countTime(long resultLong) {
        if (resultLong < 0) {
            changeToobarColor(2);
        } else {
            countDownTime(resultLong);
        }
    }

    @OnClick({R2.id.iv_back,R2.id.iv_cancel,R2.id.iv_preview,R2.id.tv_live,R2.id.tv_one,R2.id.iv_service_car})
    public void onViewClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.iv_cancel) {
            if (cancelPopUpWindow == null) {
                cancelPopUpWindow = new X3CancelPopUpWindow(this);
            }
            cancelPopUpWindow.showPopupWindow(iv_cancel, isshowred);
            cancelPopUpWindow.providerReceive(providerReceiveBaseId(), providerWorkBaseId(), 0);
            cancelPopUpWindow.setiOnItemCameraClick(this);
            cancelPopUpWindow.showWorkStatus(workBaseStatus);
        } else if (id == R.id.iv_preview) {/**
         * 预览检测报告
         */
            Bundle bundle = new Bundle();
            bundle.putBoolean("isDark", false);
            bundle.putString("title", "检测单预览检测报告页");
            bundle.putString("path", X3Constent.HOME_FINISH_DETAIL_MAIN_URL + "workBaseId=" + providerWorkBaseId() + "&carNum=" + carNum + "&type=preview&source=APP");
            X3RouterCenter.startNavigate(X3AppRouterConstants.Router.GROUND_PUSH,bundle);

        } else if (id == R.id.tv_live) {
            System.out.println("直播" + providerCarId() + " carId " + carId + " workBaseId " + providerWorkBaseId());
            X3SelectLiveTypeDialog selectLiveTypeDialog = new X3SelectLiveTypeDialog(X3MainNewTainActivity.this);
            selectLiveTypeDialog.show();
            selectLiveTypeDialog.setIonSelectOnclick(new X3SelectLiveTypeDialog.IonSelectClickListener() {
                @Override
                public void iOnselectOther() {//扫描二维码
                    SpHelper.saveData("livetype", 1);
                    Bundle bundle = new Bundle();
                    bundle.putLong("workBaseId", providerWorkBaseId());
                    X3RouterCenter.startNavigate(X3AppRouterConstants.Router.LIVE_SCAN,bundle);
                }

                @Override
                public void iOnselectLocal() {//本机直播
                    SpHelper.saveData("livetype", 0);
                    X3PointDialog pointDialog = new X3PointDialog(X3MainNewTainActivity.this, "", getString(R.string.confirm_go_live), getString(R.string.x3_cancel_info) + "", getString(R.string.x3_affirm_info));
                    pointDialog.show();
                    pointDialog.setiBtnClick(new X3PointDialog.IBtnClick() {
                        @Override
                        public void iBtnAffirmClick() {
                            if (mPresenter != null) {
                                mPresenter.generateLiveInfoOnLocal(carId, true, providerWorkBaseId());
                            }
                        }

                        @Override
                        public void iBtnCancelClick() {

                        }
                    });
                }

                @Override
                public void iOnselectUploadVideo() {//上传视频
                    long workBaseId = (long) SpHelper.getData("workBaseId" + providerWorkBaseId(), 0L);
                    if ((workBaseId != 0 && workBaseId == providerWorkBaseId()) || (!X3StringUtils.isListEmpty(uploadVideoList) && uploadVideoList.size() > 0)) {
                        Bundle bundle = new Bundle();
                        bundle.putLong("workBaseId", providerWorkBaseId());
                        bundle.putLong("carId", carId);
                        X3RouterCenter.startNavigate(X3AppRouterConstants.Router.UPLOAD_VIDEO,bundle);

                    } else {
                        isUploadVideo = true;
                        Intent intent = new Intent(X3MainNewTainActivity.this, X3CameraPhotoActivity.class);
                        intent.putExtra("isAlbum", 1);
                        intent.putExtra("allNum", 1);
                        intent.putExtra("showVideo", 1);
                        startActivity(intent);
                        overridePendingTransition(R.anim.activity_enter, 0);
                    }
                }
            });
        } else if (id == R.id.tv_one) {
            if (noticePop == null) {
                noticePop = new X3HomeNoticePop(this, getString(R.string.x3_detection_moudle), getString(R.string.x3_detection_notice));
            }
            noticePop.fromType(0);
            noticePop.show();
        } else if (id == R.id.iv_service_car) {
            showAlreadyAloneDialog();
        }
    }

    private void showAlreadyAloneDialog() {
        alreadyAloneServiceDialog = new X3BottomAlreadyAloneServiceDialog(this);
        alreadyAloneServiceDialog.show();
        alreadyAloneServiceDialog.getCurrentDetectionList(providerWorkBaseId(),needUpdateMileAndDate,carBean);
    }

    /**
     * 施工时间倒计时
     *
     * @param seconds
     */
    private void countDownTime(long seconds) {
        if (timer != null) {
            timer.cancel();
        }

        timer = new CountDownTimer(seconds, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (isFinishing()) {
                    return;
                }
                long hours = millisUntilFinished / (1000 * 60 * 60);
                long minutes = (millisUntilFinished - hours * (1000 * 60 * 60)) / (1000 * 60);
                long seconds = (millisUntilFinished - hours * (1000 * 60 * 60) - minutes * 1000 * 60) / 1000;
            }

            @Override
            public void onFinish() {
                if (isFinishing()) {
                    return;
                }
                changeToobarColor(2);
            }
        };
        timer.start();
    }

    @Override
    protected X3MainNewTainPresenter createPresenter() {
        return new X3MainNewTainPresenter();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacks(runnable);
        }
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    public void getAlone(List<AloneTitleBean> aloneTitleBeans) {
        hideLoading();
        this.aloneTitleBeans = aloneTitleBeans;
        // 题目列表
        aloneAdapter.ChangeAloneTitle(aloneTitleBeans);

        aloneAdapter.setIOnClickItem((position, title, toSystem,id,mgtCreate) -> {
            if (!X3Utils.isFastClick()) {
                return;
            }

            if (workBaseStatus > 1) {
                X3ToastUtils.showMessage(getString(R.string.x3_work_order_incorrect));
                return;
            }

            if (!isContainMe) {
                X3ToastUtils.showMessage(getString(R.string.x3_user_no_index));
                return;
            }

            if (!isStart) {
                X3ToastUtils.showMessage(getString(R.string.x3_update_work_to_do));
                return;
            }
            // 请求权限
            XXPermissions.with(X3MainNewTainActivity.this)
                    .permission(Permission.Group.STORAGE)
                    .request(new OnPermissionCallback() {
                        @Override
                        public void onGranted(List<String> permissions, boolean all) {
                            if(all){
                                startAlone(title,id,toSystem,aloneTitleBeans.get(position).isIfSubmit(),mgtCreate,-1);
                            }
                        }

                        @Override
                        public void onDenied(List<String> permissions, boolean never) {
                            //showFaild(getString(R.string.open_permiss));
                        }
                    }
        );

        });

        if (workBaseStatus <= 1) {
            int j = 0;
            for (int i = 0; i < aloneTitleBeans.size(); i++) {
                boolean ifSubmit = aloneTitleBeans.get(i).isIfSubmit();

                if (ifSubmit) {
                    j++;
                }

                // 说明题都答完了
                if (isContainMe) {
                    btn_submit.changeBtnStatus(j == aloneTitleBeans.size());
                }else {
                    btn_submit.changeBtnStatus(false);
                }
            }
        }
    }

    /**
     * 跳转到检测页面
     * @param title
     * @param id
     * @param toSystem
     * @param ifSubmit
     */
    private void startAlone(String title, long id, long toSystem, boolean ifSubmit,String mgtCreate,long jumpItemIndex) {
        Intent intent = new Intent(X3MainNewTainActivity.this, X3AloneActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("toSystemId",id);
        intent.putExtra("toSystem", toSystem);
        intent.putExtra("workBaseId", providerWorkBaseId());
        intent.putExtra("isSubmit", ifSubmit);
        intent.putExtra("carId", carId);
        intent.putExtra("reportStatus",reportStatus);
        intent.putExtra("mgtCreate",mgtCreate);
        intent.putExtra("needUpdateMile",needUpdateMileAndDate);
        intent.putExtra("carBean",carBean);
        intent.putExtra("jumpIndex",jumpItemIndex);
        startActivity(intent);
        overridePendingTransition(R.anim.activity_enter, 0);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("检测单详情页");
        boolean isQuick = getIntent().getBooleanExtra("isQuick", false);
        if (isQuick) {
            EventBus.getDefault().post("UPDATE_START_ORDER");
        }
        if (mPresenter != null && !isNotSupportLive) {
            mPresenter.endStoreLiveRoom();
        }
        if (carDialog != null) {
            carDialog.resetEtCarName();
        }
    }

    @Override
    public long providerWorkBaseId() {
        return getIntent().getLongExtra("id",0L);
    }

    @Override
    public void navigateTain(String error) {
        hideLoading();
        finish();
    }

    @Override
    public void getCancelWorkList(List<CancelWorkBean> cancelWorkBeans) {
        dialogUtil = X3BaseDialogUtil.showDialog(this, R.layout.x3_tain_cancel_service);

        RecyclerView rl_service = dialogUtil.getView(R.id.rl_view);
        dialogUtil.getView(R.id.btn_cancel).setOnClickListener(view -> {
            if (dialogUtil != null) {
                dialogUtil.dismiss();
            }
        });
        dialogUtil.getView(R.id.btn_affirm).setOnClickListener(view -> {
            if (X3StringUtils.isListEmpty(cancelList)) {
                X3ToastUtils.showMessage(getString(R.string.x3_please_select_cancel_work));
                return;
            }
            if (dialogUtil != null) {
                dialogUtil.dismiss();
            }
            if (mPresenter != null) {
                mPresenter.affirmCancelWork(cancelList, isOne);
            }
        });

        rl_service.setLayoutManager(new LinearLayoutManager(this));
        X3TainCancelAdapter tainServiceAdapter = new X3TainCancelAdapter(this, cancelWorkBeans);
        rl_service.setAdapter(tainServiceAdapter);
        tainServiceAdapter.setiOnClick(this);
    }

    @Override
    public void finishCurrent() {
        X3ToastUtils.showMessage(getString(R.string.x3_cancel_success));
        if (X3MyApp.getInstance().iAloneEventCallback != null) {
            X3MyApp.getInstance().iAloneEventCallback.iOnCancelWork(providerWorkBaseId(),externalInspectionOrderId);
        }
        DeleteFriends deleteFriends = new DeleteFriends("UPDATE_CNACEL_ORDER");
        EventBus.getDefault().post(deleteFriends);
        EventBus.getDefault().post("UPDATE_CNACEL_ORDER");
        finish();
    }

    @Override
    public void showExitPager() {
        //finish();
    }

    @Override
    public void showAdvanceWork() {
        hideLoading();
        changeToobarColor(0);
    }

    @Override
    public void showPointDialog(String content) {
        noticeDialog = new X3NoticeDialog(this, content, getString(R.string.x3_already_know));
        noticeDialog.show();
        noticeDialog.getView(R.id.btn_content).setOnClickListener(view -> finish());

        iv_preview.setVisibility(View.GONE);
        btn_submit.setVisibility(View.INVISIBLE);
        btn_before.setVisibility(View.VISIBLE);
        btn_before.changeBtnStatus(false);
    }

    @Override
    public void updateAfterWork(AdvanceTimeBean advanceTimeBean) {
        EventBus.getDefault().post("UPDATE_START_ORDER");
        DeleteFriends deleteFriends = new DeleteFriends("UPDATE_START_ORDER");
        EventBus.getDefault().post(deleteFriends);
        // 改变按钮状态
        changeToobarColor(1);

        startTime = advanceTimeBean.getStartTime();
        completeTime = advanceTimeBean.getCompleteTime();

        showStartServiceTime();
    }

    /**
     * 集中判断按钮状态
     * @param status
     */
    private void changeToobarColor(int status) {
        switch (status) {
            case 0:
                isStart = false;
                iv_preview.setVisibility(View.GONE);
                btn_submit.setVisibility(View.INVISIBLE);
                btn_before.setVisibility(View.VISIBLE);
                btn_before.changeBtnStatus(isContainMe);

                break;
            case 1:
                isStart = true;
                iv_preview.setVisibility(View.VISIBLE);
                btn_submit.setVisibility(View.VISIBLE);
                btn_before.setVisibility(View.GONE);
                btn_submit.changeBtnStatus(false);

                break;
            case 2:
                isStart = true;
                iv_preview.setVisibility(View.VISIBLE);
                btn_submit.setVisibility(View.VISIBLE);
                btn_before.setVisibility(View.GONE);
                btn_submit.changeBtnStatus(false);
                if (mHandler != null) {
                    mHandler.removeCallbacks(runnable);
                }
                mHandler.post(runnable);
                break;
        }
    }

    @Override
    public void iOnClick() {
        // 取消施工 先请求能取消的项目
        if (mPresenter != null) {
            mPresenter.getCancelWork();
        }
    }

    @Override
    public void iOnJumpToWorkDetail() {
        switch ((int) workBaseStatus) {
            case 0:
            case 1:
                if (mPresenter != null) {
                    mPresenter.getWorkBase();
                }

                break;
            default:
                Bundle bundle = new Bundle();
                bundle.putBoolean("isDark",true);
                bundle.putString("title","施工单详情页");
                bundle.putString("path", X3Constent.MAIN_TAIN_ADD_WORK + "workBaseId=" + providerWorkBaseId());
                X3RouterCenter.startNavigate(X3AppRouterConstants.Router.GROUND_PUSH,bundle);
                break;
        }
    }

    @Override
    public void iCancelOnClickListener(List<CancelWorkBean> mList, boolean isOne) {
        this.cancelList = mList;
        this.isOne = isOne;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(DeleteFriends deleteFriends) {
        String type = deleteFriends.getType();
       if ("CarCut".equals(type)){
            // 这里是首页创建接车单修改缩略图
            String imgPath = deleteFriends.getImgPath();
            long carId = deleteFriends.getCarId();
            String carNum = deleteFriends.getCarNum();

            if (carDialog != null) {
                X3ToastUtils.showMessage(getString(R.string.x3_upload_car_cut_notice));
                carDialog.changeLastCarCut(imgPath + "");
                // 上传首页创建的缩略图 切割
                if (mPresenter != null) {
                    mPresenter.uploadCarPic(carId,imgPath,carNum);
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetPictureOrVideo(CameraBean cameraBean) {
        if (cameraBean == null) {
            return;
        }
        switch ((int) cameraBean.resultCode) {
            //相册返回 集合
            case X3Constent.CODE_GALLERY_REQUEST:
                if (cameraBean.cameraData == null) {
                    return;
                }
                if(isUploadVideo){
                    List<String> pList = (List<String>) cameraBean.cameraData;
                    if (X3StringUtils.isListEmpty(pList)) {
                        return;
                    }

                    Bundle bundle = new Bundle();
                    bundle.putString("path",pList.get(0));
                    bundle.putLong("workBaseId",providerWorkBaseId());
                    bundle.putLong("carId",carId);
                    X3RouterCenter.startNavigate(X3AppRouterConstants.Router.UPLOAD_VIDEO,bundle);

                    SpHelper.saveData("workBaseId"+providerWorkBaseId(),pList.get(0));
                    Intent intent1 = new Intent(X3MainNewTainActivity.this, UploadVideoService.class);
                    intent1.putExtra("path",pList.get(0));
                    intent1.putExtra("carId",carId);
                    intent1.putExtra("workBaseId",providerWorkBaseId());
                    intent1.putExtra("isGoon",true);
                    startService(intent1);
                    isUploadVideo = false;
                }
                break;
            default:
                break;
        }
    }
    private boolean isshowred = false;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(String data) {
        switch (data){
            case "isshowred":
                isshowred = true;
                lav.setVisibility(View.VISIBLE);
                lav.setVisibility(View.VISIBLE);
                lav.setAnimation("data001.json");
                lav.setRepeatCount(Animation.INFINITE);
                lav.playAnimation();
                break;

            case "iscancelshowred":
                lav.cancelAnimation();
                lav.setVisibility(View.GONE);
                isshowred = false;
                break;
        }
    }

    @Override
    public void iOnSaveWorkSuccess(SaveWorkSuccessBean successBean,boolean isDetection) {
        iOnRefreshData();
    }

    @Override
    public void iOnRefreshData() {
        if (mPresenter != null) {
            mPresenter.obtainWorkBase();
        }
        DeleteFriends deleteFriends = new DeleteFriends("refresh");
        EventBus.getDefault().post(deleteFriends);
    }
}
